package hk.m4s.lr.repair.test.ui.equipment;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.design.widget.TabLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.bumptech.glide.Glide;
import com.jph.takephoto.model.TImage;
import com.jph.takephoto.model.TResult;
import com.lib.shortvideo.RecordShortVideoActivity;
import com.lib.shortvideo.utils.FCCache;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import framework.common.Constant;
import framework.common.alertview.AlertView;
import framework.common.alertview.OnItemClickListener;
import framework.common.baseui.UeBaseActivity;
import framework.common.takephoto.CustomHelper;
import framework.common.widgets.dialogs.UeDialog;
import framework.common.zanetwork.core.ResponseCallback;
import framework.utils.SharedPreferencesUtils;
import hk.m4s.lr.repair.test.R;
import hk.m4s.lr.repair.test.model.DeviceModel;
import hk.m4s.lr.repair.test.model.DeviceModelResult;
import hk.m4s.lr.repair.test.model.LatModel;
import hk.m4s.lr.repair.test.model.LatModelResult;
import hk.m4s.lr.repair.test.model.MainInfoModel;
import hk.m4s.lr.repair.test.model.MaintenanceInfoModel;
import hk.m4s.lr.repair.test.model.MaintenanceInfoModelResult;
import hk.m4s.lr.repair.test.model.MaintenanceModelResult;
import hk.m4s.lr.repair.test.model.MaintenanceModle;
import hk.m4s.lr.repair.test.service.AccountSerive;
import hk.m4s.lr.repair.test.service.device.DeviceListervice;
import hk.m4s.lr.repair.test.ui.adapter.DeviceMainListAdapter;
import hk.m4s.lr.repair.test.ui.adapter.DeviceSelectAdapter;
import hk.m4s.lr.repair.test.ui.adapter.DeviceSelectListAdapter;
import hk.m4s.lr.repair.test.ui.adapter.DeviceShopListAdapter;
import hk.m4s.lr.repair.test.ui.adapter.DeviceShowListAdapter;
import hk.m4s.lr.repair.test.ui.adapter.ShowPhotoAdapter;
import hk.m4s.lr.repair.test.ui.baoyang.DeviceMainTainActivity;
import hk.m4s.lr.repair.test.utils.CustomDialog;
import hk.m4s.lr.repair.test.utils.FileUtils;
import hk.m4s.lr.repair.test.utils.ToastUtil;
import hk.m4s.lr.repair.test.views.InnerGridView;
import hk.m4s.lr.repair.test.views.listview.InnerListView;
import okhttp3.Response;

/**
 * Created by qi.wang on 2017/3/23.
 * 设备维修
 */

public class DeviceRepairActivity extends UeBaseActivity implements View.OnClickListener , OnItemClickListener{
    private RelativeLayout click_fanwei, click_shop, click_repair, select_la, click_allShop;
    private LinearLayout showAncy, show_img, show_content;
    private TextView fabu_fanwei, user_shop, home_send_order, device_id, user_repair, brandS, allS, baoS,ancyTips;
    private TabLayout mTabLayout;
    private Context context;
    private ImageView show_photo, img1, img2, img3, de_cacn;
    private AlertView deAlertView;
    private Button btn_canle, btn_confirm;
    // 用于保存图片路径
    private List<TImage> imgList = new ArrayList<TImage>();
    private int selectCode = 0;
    private int deletePotion = 0;
    private String imgPath1 = "", imgPath2 = "", imgPath3 = "";
    private String imagLogo = "", imagLogo2 = "", imagLogo3 = "";
    private List<MaintenanceModle> list = new ArrayList<>();
    private DeviceSelectListAdapter deviceSelectListAdapter;
    private DeviceShopListAdapter shopListAdapter;
    InnerListView ancyList;
    List<LatModel> latModelList = new ArrayList<>();
    private View view;
    private int select = 0;
    private int state = 1;
    private int brandType = 1;
    PopupWindow popupWindow;
    private ListView select_order, de_list, info_list;
    private String id = "", type = "1", shopName = "", description = "", fabuName = "", agencyId = "", pushArea = "";
    private DeviceShowListAdapter deviceShowListAdapter;
    private List<MainInfoModel.ListBean> lists = new ArrayList<>();
    private TextView shebeiName, shebeiStyleName, baoxiuTimeName, buyTimeName, gonghuoshopName;
    String phone;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        baseSetContentView(R.layout.activity_device_repair);
        context = this;
        hiddenFooter();
        showGoBackBtn();
        setTitleText("发布维修");
        findBaseView();
        deviceMaintenanceList();
    }

    public void findBaseView() {
        click_fanwei = (RelativeLayout) findViewById(R.id.click_fanwei);
        click_shop = (RelativeLayout) findViewById(R.id.click_shop);
        click_allShop = (RelativeLayout) findViewById(R.id.click_allShop);
        click_repair = (RelativeLayout) findViewById(R.id.click_repair);
        mTabLayout = (TabLayout) findViewById(R.id.tabs);
        de_list = (ListView) findViewById(R.id.de_list);
        info_list = (ListView) findViewById(R.id.info_list);
        ancyList=(InnerListView) findViewById(R.id.ancyList);
        de_list.setOnItemClickListener(clickItem);
        info_list.setOnItemClickListener(clickItems);
        ancyList.setOnItemClickListener(clickItemss);
        select_la = (RelativeLayout) findViewById(R.id.select_la);
        showAncy= (LinearLayout) findViewById(R.id.showAncy);
        show_content = (LinearLayout) findViewById(R.id.show_content);
        fabu_fanwei = (TextView) findViewById(R.id.fabu_fanwei);
        user_repair = (TextView) findViewById(R.id.user_repair);
        user_shop = (TextView) findViewById(R.id.user_shop);
        ancyTips= (TextView) findViewById(R.id.ancyTips);
        home_send_order = (TextView) findViewById(R.id.home_send_order);
        device_id = (TextView) findViewById(R.id.device_id);
        shebeiName = (TextView) findViewById(R.id.shebeiName);
        shebeiStyleName = (TextView) findViewById(R.id.shebeiStyleName);
        baoxiuTimeName = (TextView) findViewById(R.id.baoxiuTimeName);
        buyTimeName = (TextView) findViewById(R.id.buyTimeName);
        gonghuoshopName = (TextView) findViewById(R.id.gonghuoshopName);
        btn_confirm = (Button) findViewById(R.id.btn_confirm);
        btn_canle = (Button) findViewById(R.id.btn_canle);
        baoS = (TextView) findViewById(R.id.baoS);
        brandS = (TextView) findViewById(R.id.brandS);
        allS = (TextView) findViewById(R.id.allS);
        baoS.setOnClickListener(this);
        brandS.setOnClickListener(this);
        allS.setOnClickListener(this);
        click_allShop.setOnClickListener(this);
        user_repair.setOnClickListener(this);
        btn_confirm.setOnClickListener(this);
        btn_canle.setOnClickListener(this);
        click_repair.setOnClickListener(this);
        home_send_order.setOnClickListener(this);

        click_fanwei.setOnClickListener(this);
        click_shop.setOnClickListener(this);
        deviceSelectListAdapter = new DeviceSelectListAdapter(context, list);
        de_list.setAdapter(deviceSelectListAdapter);
        mTabLayout.setTabMode(TabLayout.MODE_FIXED);
        mTabLayout.addTab(mTabLayout.newTab().setText("指定商家"), true);
        mTabLayout.addTab(mTabLayout.newTab().setText("所有商家"));
        mTabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (tab.getPosition() == 0) {
                    brandType = 1;
                    click_shop.setVisibility(View.VISIBLE);
                    click_allShop.setVisibility(View.GONE);
                    showAncy.setVisibility(View.GONE);
                } else {
                    brandType = 2;
                    click_shop.setVisibility(View.GONE);
                    click_allShop.setVisibility(View.VISIBLE);
                    showAncy.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.click_fanwei:
                select = 0;
                shopName = "";
                select_la.setVisibility(View.VISIBLE);
                de_list.setVisibility(View.VISIBLE);
                info_list.setVisibility(View.GONE);
                break;
            case R.id.click_shop:
                select = 1;

                de_list.setVisibility(View.GONE);
                info_list.setVisibility(View.VISIBLE);
                if (id.equals("")) {
                    ToastUtil.toast(context, "请选择维修单");
                } else {
                    select_la.setVisibility(View.VISIBLE);
                    deviceMaintenanceInfos(id);
                }
                break;
            case R.id.btn_canle:
                if (select == 0) {
                    fabuName = "";
                    select_la.setVisibility(View.GONE);
                    fabu_fanwei.setText("请选择维修单");
                } else {
                    shopName = "";
                    select_la.setVisibility(View.GONE);
                    user_shop.setText("请选择指定服务商户");
                }
                break;
            case R.id.btn_confirm:
                if (select == 0) {
                    select_la.setVisibility(View.GONE);
                    fabu_fanwei.setText(fabuName);
                    if (!id.equals("")) {
                        deviceMaintenanceInfos(id);
                    }
                } else {
                    select_la.setVisibility(View.GONE);
                    user_shop.setText(shopName);
                }
                break;
            case R.id.click_allShop:

                break;
            case R.id.home_send_order:
                if (id.equals("")) {
                    ToastUtil.toast(context, "请选择维修单");
                    return;
                }
                if (brandType == 1) {
                    if (agencyId.equals("")) {
                        ToastUtil.toast(context, "请选择服务商户");
                        return;
                    }
                } else {
                    if (state == 0) {
                        ToastUtil.toast(context, "请选择服务商户");
                        return;
                    }
                }
                deviceMaintenancePush();
                break;
            case R.id.brandS:
                state = 1;
                Drawable drawable = getResources().getDrawable(R.mipmap.checked_hover);
                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                brandS.setCompoundDrawables(drawable, null, null, null);
                Drawable drawables = getResources().getDrawable(R.mipmap.check);
                drawables.setBounds(0, 0, drawables.getMinimumWidth(), drawables.getMinimumHeight());
                allS.setCompoundDrawables(drawables, null, null, null);
                if (id.equals("")) {
                    ToastUtil.toast(context, "请选择维修单");
                } else {
                    deviceMaintenanceInfos(id);
                }
                break;
            case R.id.allS:
                state = 2;

                Drawable dra = getResources().getDrawable(R.mipmap.checked_hover);
                dra.setBounds(0, 0, dra.getMinimumWidth(), dra.getMinimumHeight());
                allS.setCompoundDrawables(dra, null, null, null);
                Drawable drs = getResources().getDrawable(R.mipmap.check);
                drs.setBounds(0, 0, drs.getMinimumWidth(), drs.getMinimumHeight());
                brandS.setCompoundDrawables(drs, null, null, null);
                if (id.equals("")) {
                    ToastUtil.toast(context, "请选择维修单");
                } else {
                    deviceMaintenanceInfos(id);
                }

                break;
            case R.id.user_repair:
                type = "1";
                Drawable drarepair = getResources().getDrawable(R.mipmap.checked_hover);
                drarepair.setBounds(0, 0, drarepair.getMinimumWidth(), drarepair.getMinimumHeight());
                user_repair.setCompoundDrawables(drarepair, null, null, null);
                Drawable drbaoS = getResources().getDrawable(R.mipmap.check);
                drbaoS.setBounds(0, 0, drbaoS.getMinimumWidth(), drbaoS.getMinimumHeight());
                baoS.setCompoundDrawables(drbaoS, null, null, null);
                break;
            case R.id.baoS:

                if (brandType == 2) {
                    ToastUtil.toast(context, "所有商家不支持保修");
                } else {
                    type = "2";
                    Drawable drarepairs = getResources().getDrawable(R.mipmap.checked_hover);
                    drarepairs.setBounds(0, 0, drarepairs.getMinimumWidth(), drarepairs.getMinimumHeight());
                    baoS.setCompoundDrawables(drarepairs, null, null, null);
                    Drawable drbaoSs = getResources().getDrawable(R.mipmap.check);
                    drbaoSs.setBounds(0, 0, drbaoSs.getMinimumWidth(), drbaoSs.getMinimumHeight());
                    user_repair.setCompoundDrawables(drbaoSs, null, null, null);
                }
                break;
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
    }


    public void deviceMaintenanceList() {
        Map<String, Object> parmas = new HashMap<>();
        parmas.put("device_type", Constant.device_type);
        parmas.put("token", SharedPreferencesUtils.getSharedPreferences(Constant.token, ""));
        try {
            JSONObject jsondata = new JSONObject();
            jsondata.put("noPage", "0");
            parmas.put("jsonText", jsondata.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        DeviceListervice.deviceLists(context, parmas, new ResponseCallback<MaintenanceModelResult>() {
            @Override
            public void onSuccess(MaintenanceModelResult accountModel) {
                list.clear();
                if (accountModel.getList() != null) {
                    list.addAll(accountModel.getList());
                    deviceSelectListAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onError(Response response, int errorCode, String errorMsg, Exception e) {

            }
        });
    }

    private void showWindow(View parent) {

        if (popupWindow == null) {
            LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            view = layoutInflater.inflate(R.layout.slect_layout, null);

            select_order = (ListView) view.findViewById(R.id.select_order);
            // 创建一个PopuWidow对象
            popupWindow = new PopupWindow(view, WindowManager.LayoutParams.MATCH_PARENT, 350);
        }

        select_order.setAdapter(deviceSelectListAdapter);
        select_order.setOnItemClickListener(clickItem);
        // 使其聚集
        popupWindow.setFocusable(true);
        // 设置允许在外点击消失
        popupWindow.setOutsideTouchable(true);

        // 这个是为了点击“返回Back”也能使其消失，并且并不会影响你的背景
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        // 显示的位置为:屏幕的宽度的一半-PopupWindow的高度的一半
        int xPos = windowManager.getDefaultDisplay().getWidth() / 2
                - popupWindow.getWidth() / 2;
        Log.i("coder", "xPos:" + xPos);

        popupWindow.showAsDropDown(parent, xPos, 0);

        select_order.setOnItemClickListener(clickItem);
    }


    public void pusnFabu() {
        Map<String, Object> parmas = new HashMap<>();
        parmas.put("device_type", Constant.device_type);
        parmas.put("token", SharedPreferencesUtils.getSharedPreferences(Constant.token, ""));
        try {
            JSONObject jsondata = new JSONObject();
            jsondata.put("pid", "-6");
            parmas.put("jsonText", jsondata.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        AccountSerive.pushFabu(context, parmas, new ResponseCallback<LatModelResult>() {
            @Override
            public void onSuccess(LatModelResult accountModel) {
                if (accountModel.getList() != null) {
                    latModelList.clear();
                    latModelList.addAll(accountModel.getList());
                    // shopListAdapter = new DeviceShopListAdapter(context, latModelList);
                    // de_list.setAdapter(shopListAdapter);
                    shopListAdapter.flag = 0;
                    shopListAdapter.notifyDataSetChanged();
                    shopName = latModelList.get(0).getName();
                    agencyId = String.valueOf(latModelList.get(0).getId());
                }
            }

            @Override
            public void onError(Response response, int errorCode, String errorMsg, Exception e) {

            }
        });
    }

    AdapterView.OnItemClickListener clickItem = new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                long arg3) {
            // TODO Auto-generated method stub
            MaintenanceModle deviceModel = list.get(arg2);
            deviceSelectListAdapter.flag = arg2;
            deviceSelectListAdapter.notifyDataSetChanged();
            if (select == 0) {
                fabuName = deviceModel.getMaintenanceOrder();
                id = deviceModel.getId();

            }
        }

    };
    AdapterView.OnItemClickListener clickItems = new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                long arg3) {
            // TODO Auto-generated method stub
            MainInfoModel.ListBean deviceModel = lists.get(arg2);
            shopName = deviceModel.getName();
            if (!(deviceModel.getSupplierId() == null || deviceModel.getSupplierId().equals(""))) {
                agencyId = deviceModel.getSupplierId();
            }
            deviceShowListAdapter.flag = arg2;
            deviceShowListAdapter.notifyDataSetChanged();
        }

    };

    public void deviceMaintenanceInfos(final String id) {
        Map<String, Object> parmas = new HashMap<>();
        parmas.put("device_type", Constant.device_type);
        parmas.put("token", SharedPreferencesUtils.getSharedPreferences(Constant.token, ""));
        try {
            JSONObject jsondata = new JSONObject();
            jsondata.put("id", id);
            jsondata.put("type", brandType);
            if (brandType == 2) {
                jsondata.put("supplierType", state);
            }
            jsondata.put("lat", SharedPreferencesUtils.getSharedPreferences(Constant.Latitude, ""));
            jsondata.put("lng", SharedPreferencesUtils.getSharedPreferences(Constant.Longitude, ""));
            parmas.put("jsonText", jsondata.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        DeviceListervice.deviceCheckInfo(context, parmas, new ResponseCallback<MainInfoModel>() {
            @Override
            public void onSuccess(MainInfoModel accountModel) {
                lists.clear();
                if (accountModel != null) {
                    shebeiName.setText(accountModel.getTitle());
                    shebeiStyleName.setText(accountModel.getModel());
                    if (accountModel.getWarranty() == 0) {
                        baoxiuTimeName.setText("暂无数据");
                    } else {
                        baoxiuTimeName.setText(accountModel.getWarranty() + "");
                    }
                    buyTimeName.setText(accountModel.getPayTime());
                    gonghuoshopName.setText(accountModel.getSupplierName());
                    if (accountModel.getList() != null) {
                        show_content.setVisibility(View.VISIBLE);
                        home_send_order.setVisibility(View.VISIBLE);
                        lists.addAll(accountModel.getList());
                        if(accountModel.getList().size()>0) {
                            ancyTips.setVisibility(View.GONE);
                        }else{
                            ancyTips.setVisibility(View.VISIBLE);
                        }
                        if (brandType == 2) {
                            deviceShowListAdapter = new DeviceShowListAdapter(context, lists);
                            ancyList.setAdapter(deviceShowListAdapter);
                        }else {
                            deviceShowListAdapter = new DeviceShowListAdapter(context, lists);
                            info_list.setAdapter(deviceShowListAdapter);
                        }
                    }else{
                        ancyTips.setVisibility(View.VISIBLE);
                    }
                }

            }

            @Override
            public void onError(Response response, int errorCode, String errorMsg, Exception e) {

            }
        });
    }

    public void deviceMaintenancePush() {
        Map<String, Object> parmas = new HashMap<>();
        parmas.put("device_type", Constant.device_type);
        parmas.put("token", SharedPreferencesUtils.getSharedPreferences(Constant.token, ""));
        try {
            JSONObject jsondata = new JSONObject();
            jsondata.put("id", id);
            jsondata.put("type", type);
            if (brandType == 1) {
                if (!agencyId.equals("")) {
                    jsondata.put("supplierId", new JSONArray().put(agencyId));
                }
            } else {
                JSONArray array = new JSONArray();
                for (MainInfoModel.ListBean bean : lists) {
                    if (!bean.getSupplierId().equals("")) {
                        array.put(bean.getSupplierId());
                    }
                }
                if (array.length() > 0) {
                    jsondata.put("supplierId", array.toString());
                }
            }
            parmas.put("jsonText", jsondata.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        DeviceListervice.deviceCheckPush(context, parmas, new ResponseCallback<MaintenanceInfoModelResult>() {
            @Override
            public void onSuccess(MaintenanceInfoModelResult accountModel) {
                ToastUtil.toast(context, "操作成功");
                finish();
            }

            @Override
            public void onError(Response response, int errorCode, String errorMsg, Exception e) {

            }
        });
    }
    AdapterView.OnItemClickListener clickItemss = new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                long arg3) {
            // TODO Auto-generated method stub
            MainInfoModel.ListBean deviceModel = lists.get(arg2);
            phone=deviceModel.getPhone();
            select=2;
            new AlertView("提示", "是否要拨打电话", "取消", new String[]{"确定"}, null, DeviceRepairActivity.this, AlertView.Style.Alert, DeviceRepairActivity.this).setCancelable(true).show();
        }

    };
    @Override
    public void onItemClick(Object o, int position) {
        //判断是否是拓展窗口View，而且点击的是非取消按钮
        if (position == -1) {
            return;
        } else {
            if (position == 0) {
                    if(!(phone==null||phone.equals(""))){
                        if (ContextCompat.checkSelfPermission(((Activity) context),
                                Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                            // 没有获得授权，申请授权
                            if (ActivityCompat.shouldShowRequestPermissionRationale(((Activity) context),
                                    Manifest.permission.CALL_PHONE)) {
                                // 返回值：
//                          如果app之前请求过该权限,被用户拒绝, 这个方法就会返回true.
//                          如果用户之前拒绝权限的时候勾选了对话框中”Don’t ask again”的选项,那么这个方法会返回false.
//                          如果设备策略禁止应用拥有这条权限, 这个方法也返回false.
                                // 弹窗需要解释为何需要该权限，再次请求授权
                                // 帮跳转到该应用的设置界面，让用户手动授权
                                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                Uri uri = Uri.fromParts("package", context.getPackageName(), null);
                                intent.setData(uri);
                                context.startActivity(intent);
                            } else {
                                // 不需要解释为何需要该权限，直接请求授权
                                ActivityCompat.requestPermissions(((Activity) context),
                                        new String[]{Manifest.permission.CALL_PHONE},
                                        1);
                            }
                        } else {
                            Intent phoneIntent = new Intent("android.intent.action.CALL", Uri.parse("tel:" +phone));
                            context.startActivity(phoneIntent);
                        }
                    }else{
                        ToastUtil.toast(context,"电话不正确");
                    }
                }
        }
    }
}
